package cn.com.yangzhenyu;

import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

public class MyWordToHtml {

    public static void main(String[] args) throws IOException {
        String filePathName = "d://abc.docx";
        MyWordToHtml main = new MyWordToHtml();
        InputStream in = new FileInputStream(new File(filePathName));
        // 1.加载解析docx文档用的XWPFDocument对象
        XWPFDocument document = new XWPFDocument(in);
        String html = main.docxToHtml(document);
        System.out.println(html);
    }

    public String docxToHtml(XWPFDocument document){
        String value = "";
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            XHTMLConverter.getInstance().convert(document, outputStream, null);

            value = new String(outputStream.toByteArray());
        } catch (Exception e){
            e.printStackTrace();
        }
        return value;
    }

    /**
     * doc格式转html
     * @param wordDocument
     * @return
     */
    public String docToHtml(HWPFDocument wordDocument) {
        String content = null;
        ByteArrayOutputStream baos = null;
        try {
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();
            DOMSource domSource = new DOMSource(htmlDocument);
            baos = new ByteArrayOutputStream();
            StreamResult streamResult = new StreamResult(baos);

            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer serializer = tf.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    content = new String(baos.toByteArray(), "utf-8");
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return content;
    }
}
